package com.example.demo.config;

import com.example.demo.model.FileSource;
import com.example.demo.service.FileService;
import com.netflix.discovery.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * FileService的工厂
 * 将各个实现类放入map
 */
@Configuration
public class FileServiceFactory {
    private Map<FileSource, FileService> map = new HashMap<>();

    @Autowired
    private FileService localFileServiceImpl;
    @Autowired
    private FileService aliyunFileServiceImpl;

    @PostConstruct
    public void init(){
        map.put(FileSource.LOCAL, localFileServiceImpl);
        map.put(FileSource.ALIYUN, aliyunFileServiceImpl);
    }

    /**
     * 根据文件源获取具体的实现类
     * @param filesource 文件源
     * @return
     */
    public FileService getFileService(String filesource){
        if(StringUtils.isBlank(filesource)){
            return localFileServiceImpl;
        }

        FileService fileService = map.get(FileSource.valueOf(filesource));
        if (fileService == null) {
            throw new IllegalArgumentException("请检查FileServiceFactory类的init方法，看是否有" + filesource + "对应的实现类");
        }
        return fileService;
    }

}
